#include "mysqlop.h"
#include "common.h"

MysqlOp::MysqlOp()
{
    // 连接到 MySQL 数据库
    db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost"); // MySQL 服务器地址
    db.setDatabaseName("QMYSQL"); // 数据库名
    db.setUserName("debian-sys-maint"); // 用户名
    db.setPassword("EaorsBJEEr57TRKe"); // 密码

    if (!db.open())
    {
        qDebug() << "无法连接到数据库";
    }
    else
    {
        qDebug() << "链接到数据库成功";
    }
}


void MysqlOp::insertData(const QString& data)
{
    QSqlQuery query;
    query.prepare("INSERT INTO table_name (column_name) VALUES (:data)");
    query.bindValue(":data", data);

    if (!query.exec())
    {
        qDebug() << "插入数据失败:" << query.lastError().text();
    }
}

//查询位置
void MysqlOp::queryPosition1(int index)
{
    // int num = 0;
    QSqlQuery query("SELECT * FROM position1");
    while (query.next())
    {
        QString day0 = query.value(0).toString();
        QString stationid = query.value(1).toString();
        QString name = query.value(2).toString();
        qDebug() << "stationid:" << stationid << name;


        // Reading x1 to x4 as strings
        QString x1 = query.value(3).toString();
        QString y1 = query.value(4).toString();
        QString x2 = query.value(5).toString();
        QString y2 = query.value(6).toString();
        QString x3 = query.value(7).toString();
        QString y3 = query.value(8).toString();
        QString x4 = query.value(9).toString();
        QString y4 = query.value(10).toString();

        // Converting x1 to x4 to double
        zuoshang.x = x1.toDouble() * (480 / 120);
        zuoshang.y = y1.toDouble()* (480 / 120);
        youshang.x = x2.toDouble()* (480 / 120);
        youshang.y = y2.toDouble()* (480 / 120);
        zuoxia.x = x3.toDouble()* (480 / 120);
        zuoxia.y = y3.toDouble()* (480 / 120);
        youxia.x = x4.toDouble()* (480 / 120);
        youxia.y = y4.toDouble()* (480 / 120);

        if(QString::number(index) == stationid)
            break;
    }
}

// 查询数据
QString MysqlOp::queryData()
{
    QSqlQuery query("SELECT * FROM plc3");
    while (query.next())
    {
        QString concatenatedString;
        for (int i = 0; i < 10; ++i) {
            concatenatedString += query.value(i).toString();
            if (i < 9) {
                concatenatedString += " "; // 添加空格分隔符
            }
        }
        return concatenatedString;
        qDebug() << "Concatenated string: " << concatenatedString;
    }
}

// 删除数据
void MysqlOp::deleteData(int id)
{
    QSqlQuery query;
    query.prepare("DELETE FROM table_name WHERE id = :id");
    query.bindValue(":id", id);

    if (!query.exec()) {
        qDebug() << "删除数据失败:" << query.lastError().text();
    }
}
